package cn.msqweb.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
@Slf4j
public class JwtJson {
    private static Map<String,Object> JWT_HEAD;
    private static String SIGNATURE = "123*DAW!@#$$DSA{<";
    {
        JWT_HEAD.put("alg","HS256");
        JWT_HEAD.put("typ","JWT");
    }

    /**
     * 创建JWT
     * @param objJson
     * @return
     */
    public static String createJWT(String objJson){
        return JWT.create()
                .withHeader(JWT_HEAD)
                .withClaim("users", objJson)
                .sign(Algorithm.HMAC256(SIGNATURE));
    }

    /**
     * 验证JWT
     * @param jwt
     * @return
     */
    public static boolean verifyJWT(String jwt){
        try {
            JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGNATURE)).build();
            build.verify(jwt);
            return true;
        } catch (Exception e) {
            log.error("JWT验证失败");
            return false;
        }
    }


    /**
     * 解析JWT
     * @param jwt
     * @return
     */
        public static String parseJWT(String jwt){
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SIGNATURE)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            return decodedJWT.getClaim("users").asString();
        }
}
